<?php
// 本类由系统自动生成，仅供测试用途
class NewsAction extends Action {

    public function index(){
		header('Location: http://product.dushijia.com/');
		exit;
		$this->display(); // 输出模板

    }

	//新闻列表
	public function lists(){
		$f = $this->_get('f'); //父分类
		$c = $this->_get('c'); //本分类
		
		$Category =   M('Category');
		
		$oneArr = $Category->where("catdir='$c'")->find();
		$catid = $oneArr['catid'];
		$catname = $oneArr['catname'];
		$caturl = $oneArr['url'];
		
		if($catid){
			Load('extend');
			//取到父分类信息，显示在导航上
			$parentArr = $Category->where("catdir='$f'")->find();
			$parentId = $parentArr['catid'];
			$parentName = $parentArr['catname'];
			$parentUrl = $parentArr['url'];
			
			//右侧同类信息
			$allsonArr = $Category->where("parentid='$parentId'")->select();

			$Product =   M('Product');
			import("ORG.Util.Page");// 导入分页类
			$p = $this->_get('p');
			$nowPage = isset($p)?$p:1;
			$where = "catid=$catid AND title!=''";
			$count      = $Product->where($where)->count();// 查询满足要求的总记录数
			$Page       = new Page($count,33);// 实例化分页类 传入总记录数
			$list = $Product->where($where)->order('id desc')->page($nowPage.','.$Page->listRows)->select();
			//特殊处理URL
			$Page->url = U('/'.$f.'/'.$c.'/__PAGE__');
			$Page->kylingood = 1;
			$Page->rollPage = 5;
			$pageshow       = $Page->show();// 分页显示输出


			//精华推荐
			$goodArr = $Product->query("SELECT `v9_product`.*,v9_position_data.* FROM `v9_product` 
left join `v9_position_data` on  `v9_product`.id=`v9_position_data`.id  WHERE  `v9_product`.title!=''  AND  v9_product.catid=$catid  AND  v9_position_data.posid IN (1,2,3,4,5,6,7,8,9,10) order by `v9_product`.id desc limit 0,10");

			//热文排行
			$rankArr = $Product->query("SELECT `v9_product`.* FROM `v9_product` WHERE `v9_product`.title!='' AND catid=$catid AND  ORDER BY `v9_product`.id DESC LIMIT 0 , 10");

			//图片列表
			$imgArr = $Product->query("SELECT `v9_product`.* FROM `v9_product` WHERE `v9_product`.title!='' AND catid=$catid AND thumb!=''   ORDER BY `v9_product`.id DESC LIMIT 0 , 4");

			//热门新闻
			$hotArr = $Product->query("SELECT `v9_product`.*,v9_product.thumb as newsthumb,v9_position_data.* FROM `v9_product` 
left join `v9_position_data` on  `v9_product`.id=`v9_position_data`.id  WHERE `v9_product`.title!='' AND  v9_product.thumb!='' AND v9_position_data.posid in (1,2,3,4,5,6,7,8,9)   order by `v9_product`.id desc limit 0,10");
			
			//热门新闻
			$hotProduct = $Product->query("SELECT * FROM `v9_news` WHERE `v9_news`.title!=''  AND thumb!=''ORDER BY id DESC LIMIT 0 , 10");
			
			
			$this->assign('goodArr',$goodArr);// 精华推荐
			$this->assign('rankArr',$rankArr);// 热文排行
			$this->assign('imgArr',$imgArr);// 图片列表
			$this->assign('hotArr',$hotArr);// 热门新闻
			$this->assign('hotProduct',$hotProduct);// 热门新闻


			$this->assign('catname',$catname);// 栏目名
			$this->assign('caturl',$caturl);// 栏目链接地址
			$this->assign('page',$pageshow);// 赋值分页输出
			$this->assign('list',$list);// 赋值数据集
			$this->assign('allsonArr',$allsonArr);// 右侧同类信息
			

			//SEO相关

			$SEO['title'] = $catname.'-都市家建材网';
			$SEO['keywords'] =  $catname.',都市家建材网,建材网,建材网站,建材产品供应,建材产品求购';
			$SEO['description'] = '都市家建材网提供专业且全面的建材产品供求信息,主要信息包含:建材产品的报价,建材产品的品牌,建材产品的招商，加盟以及建材代理信息,为广大建材行业的个人与企业同行们，提供海量的建材信息与商机，努力打造成中国最全的建材种类行业门户网站.';
			$this->assign('SEO',$SEO);// SEO相关
			//导航
			$NAV_LIST = '<a href="http://www.dushijia.com" title="网站首页" target="_blank">网站首页</a> &gt; 
			<a href="http://product.dushijia.com" title="建材产品" target="_blank">建材产品</a> &gt; 
			<a href="'.$parentUrl.'" title="'.$parentName.'" target="_blank">'.$parentName.'</a> &gt;'.$catname;
			$this->assign('NAV_LIST',$NAV_LIST);

			$this->display(); // 输出模板
		}else{
			header("HTTP/1.0 404 Not Found");
			header('Location: http://www.dushijia.com/error/404.html');
			exit;
		}
	
	}



	//频道列表
	public function category(){
		$f = $this->_get('f'); //父分类
		$c = $this->_get('c'); //本分类
		
		$Category =   M('Category');
		
		$oneArr = $Category->where("catdir='$c'")->find();
		$catid = $oneArr['catid'];
		$catname = $oneArr['catname'];
		$caturl = $oneArr['url'];
		$arrchildid = $oneArr['arrchildid'];
		
		
		if($catid){
			Load('extend');
			//取到父分类信息，显示在导航上
			$parentArr = $Category->where("catdir='$f'")->find();
			$parentId = $parentArr['catid'];
			$parentName = $parentArr['catname'];
			$parentUrl = $parentArr['url'];
			
			//右侧同类信息
			$allsonArr = $Category->where("parentid='$catid'")->select();

			$Product =   M('Product');
			import("ORG.Util.Page");// 导入分页类
			$p = $this->_get('p');
			$nowPage = isset($p)?$p:1;
			$where = "catid IN ($arrchildid ) AND title!=''";
			$count      = $Product->where($where)->count();// 查询满足要求的总记录数
			$Page       = new Page($count,33);// 实例化分页类 传入总记录数
			$list = $Product->where($where)->order('id desc')->page($nowPage.','.$Page->listRows)->select();
			//特殊处理URL
			$Page->url = U('/'.$c.'/__PAGE__');
			$Page->kylingood = 1;
			$Page->rollPage = 5;
			$pageshow       = $Page->show();// 分页显示输出


			//精华推荐
			$goodArr = $Product->query("SELECT `v9_product`.*,v9_position_data.* FROM `v9_product` 
left join `v9_position_data` on  `v9_product`.id=`v9_position_data`.id  WHERE  `v9_product`.title!=''  AND  v9_product.catid IN ($arrchildid )  AND  v9_position_data.posid IN (1,2,3,4,5,6,7,8,9,10) order by `v9_product`.id desc limit 0,10");

			//热文排行
			$rankArr = $Product->query("SELECT `v9_product`.* FROM `v9_product` WHERE `v9_product`.title!='' AND catid IN ($arrchildid ) AND  ORDER BY `v9_product`.id DESC LIMIT 0 , 10");

			//图片列表
			$imgArr = $Product->query("SELECT `v9_product`.* FROM `v9_product` WHERE `v9_product`.title!='' AND catid IN ($arrchildid ) AND thumb!=''   ORDER BY `v9_product`.id DESC LIMIT 0 , 4");

			//热门新闻
			$hotArr = $Product->query("SELECT `v9_product`.*,v9_product.thumb as newsthumb,v9_position_data.* FROM `v9_product` 
left join `v9_position_data` on  `v9_product`.id=`v9_position_data`.id  WHERE `v9_product`.title!='' AND  v9_product.thumb!='' AND v9_position_data.posid in (1,2,3,4,5,6,7,8,9)   order by `v9_product`.id desc limit 15,10");
			
			//热门新闻
			$hotProduct = $Product->query("SELECT * FROM `v9_news` WHERE `v9_news`.title!=''AND thumb!=''ORDER BY id DESC LIMIT 0 , 10");
			
			
			$this->assign('goodArr',$goodArr);// 精华推荐
			$this->assign('rankArr',$rankArr);// 热文排行
			$this->assign('imgArr',$imgArr);// 图片列表
			$this->assign('hotArr',$hotArr);// 热门新闻
			$this->assign('hotProduct',$hotProduct);// 热门新闻


			$this->assign('catname',$catname);// 栏目名
			$this->assign('caturl',$caturl);// 栏目链接地址
			$this->assign('page',$pageshow);// 赋值分页输出
			$this->assign('list',$list);// 赋值数据集
			$this->assign('allsonArr',$allsonArr);// 右侧同类信息
			

			//SEO相关
			$SEO['title'] = $catname.'-都市家建材网';
			$SEO['keywords'] =  $catname.',都市家建材网,建材网,建材网站,建材产品供应,建材产品求购';
			$SEO['description'] = '都市家建材网提供专业且全面的建材产品供求信息,主要信息包含:建材产品的报价,建材产品的品牌,建材产品的招商，加盟以及建材代理信息,为广大建材行业的个人与企业同行们，提供海量的建材信息与商机，努力打造成中国最全的建材种类行业门户网站.';
			$this->assign('SEO',$SEO);// SEO相关

			//导航
			$NAV_LIST = '<a href="http://www.dushijia.com" title="网站首页" target="_blank">网站首页</a> &gt; 
			<a href="http://product.dushijia.com" title="建材产品" target="_blank">建材产品</a> &gt;'.$catname;
			$this->assign('NAV_LIST',$NAV_LIST);

			$this->display(); // 输出模板
		}else{
			header("HTTP/1.0 404 Not Found");
			header('Location: http://www.dushijia.com/error/404.html');
			exit;
		}
	
	}

	public function show(){

		
		$id = $this->_get('id');
		
		
		$Product =   M('Product');
		$newsArr = $Product->query("SELECT `v9_product`.*,`v9_product_data`.*, v9_category.catname,v9_category.url as caturl FROM `v9_product` 
left join `v9_product_data` on  `v9_product`.id=`v9_product_data`.id 
left join v9_category on `v9_product`.catid=`v9_category`.catid  where `v9_product`.id = $id");
		if(count($newsArr)){
			import("ORG.Util.Sphinxapi");// 导入Sphinx类
			import("ORG.Util.Pinyin");// 导入Pinyin类
			$title = $keyword = $newsArr[0]['title'];
			$keywords = $newsArr[0]['keywords'];
			$catid = $newsArr[0]['catid'];

			$Category =   M('Category');
			$parentArr = $Category->where("catid='$catid'")->find();
			$parentId = $parentArr['parentid'];
			
			$parentArr = $Category->where("catid='$parentId'")->find();
			$parentId = $parentArr['catid'];
			$parentName = $parentArr['catname'];
			$parentUrl = $parentArr['url'];

			$catname = $newsArr[0]['catname'];
			$caturl = $newsArr[0]['caturl'];
			$description = $newsArr[0]['description'];
			$relation = $newsArr[0]['relation'];//产品相关推荐
			$relation_news = $newsArr[0]['relation_news'];//文章相关推荐
			//去掉为0的ID，且把重复性的ID也去掉
			$relationArr = array_unique(array_filter(explode("|",$relation)));
			$relationNewsArr = array_unique(array_filter(explode("|",$relation_news)));

			
			$newsArr[0]['description'] = $description =  addslashes(strip_tags($newsArr[0]['description']));
			Load('extend');
			if($description == ''){

				$newsArr[0]['description'] = $description = addslashes(msubstr(strip_tags($newsArr[0]['content']),0,310));

				$sql = "UPDATE `v9_product` SET description = '$description' WHERE id=$id";

				$re = $Product->query($sql);
			}
			$SeoDescription = $newsArr[0]['description'] = msubstr($description,0,310);

			$Pinyin = new Pinyin();
			//如果有关键词，则直接搜索
			$keywordArr = explode(" ",$keywords);
			$nums = count($keywordArr);
			if($keywords && $nums >1){
				foreach($keywordArr as $k=>$val){
					$pinyin = $Pinyin->get($val,'utf-8');
					$keywordList[$k]['name'] = $val;
					$keywordList[$k]['pinyin'] = $pinyin;
				}
			}
			
			//如果相关文章小于21篇，则重新取一次相关文章
			if(count($relationArr)<11 || $nums<=1){
				
				//这里是增加的搜索
				$sphinx = new SphinxClient();
				//$sphinx->SetServer('localhost','9312');
				$sphinx->SetServer('218.106.98.186','9312');
				$sphinx->SetConnectTimeout(1);
				
				$sphinx->SetLimits(0,25);

				$wordresult = $sphinx->query($keyword,'productmain');
				$sphinx->SetMatchMode(SPH_MATCH_EXTENDED);
				$sphinx->SetSortMode (SPH_SORT_EXPR,"@weight*50000+ln(inputtime)*100000" );
				$string='';
				
				
				//如果有关键词，则直接搜索
				if($keywords && $nums>1){
					foreach($keywordArr as $k=>$val){
						$arrword[]='@title '.$val;
						$pinyin = $Pinyin->get($val,'utf-8');
						$keywordList[$k]['name'] = $val;
						$keywordList[$k]['pinyin'] = $pinyin;
						$seo_Arr[] = $val;
					}
					$string = implode(' | ',$arrword);
				
				}else{
				
					//查找标题有的关键词
					if(is_array($wordresult['words'])){
						foreach($wordresult['words'] as $key=>$val){
							$arrword[]='@title '.$key;
							
							$seo_Arr[] = $key;
							//把关键词按字符长度存为key
							$newarr[$key] = strlen($key);
						}
						$string = implode(' | ',$arrword);
					}else{
						$string='@title '.$keyword;
						
						$newarr[$keyword] = strlen($keyword);
						$seo_Arr[] = $keyword;
						
					}
					//按分词字节数排序，得到前5个分词词组
					
					//按数组key倒序排列
					arsort($newarr);
					//截取前5位关键词
					array_splice($newarr, 5);
					$keyArr = array_filter(array_keys($newarr));
					$keywords = addslashes(implode(' ',array_unique(array_splice($keyArr, 5))));
					unset($keywordList);
					if(is_array($keyArr))foreach($keyArr as $k=>$val){
						$pinyin = $Pinyin->get($val,'utf-8');
						$keywordList[$k]['name'] = $val;
						$keywordList[$k]['pinyin'] = $pinyin;
						$seo_Arr[] = $val;
					}
					
					if(count($keyArr) >0 ){
						$sql = "UPDATE `v9_product` SET `keywords` = '$keywords' WHERE `v9_product`.`id` ='$id'";
						$re = $Product->query($sql);
					}
				}
				
				$result = $sphinx->query($string,'productmain');

				
				$TotalResult = $result['total_found'];
				
				
				if(is_array($result["matches"])){
					foreach ( $result["matches"] as $doc => $docinfo ) {
						$idarr[] = $doc;
					}

					
							
					$newresult = $sphinx->query($string,'main');
					foreach ( $newresult["matches"] as $doc => $docinfo ) {
						$newsidarr[] = $doc;
					}	
					
					$relationids = implode('|',$idarr);//把相关ID存入到数据库中
					$relation_news = implode('|',$newsidarr);//把相关新闻ID存入到数据库中
					$Product->query("UPDATE v9_product_data  set relation='$relationids',relation_news='$relation_news'  where id =$id");
				}
				/*
				$options = array(
							'before_match'          => '<font color="red">',
							'after_match'           => '</font>',
							'chunk_separator'       => '',
							'limit'                 => 300,
							'around'                => 10,
				);
				
				foreach($list as $key=>$Arr){
					$height_title[0] = $Arr['title'];
					//$height_content[0] = strip_tags($Arr['content']);
					$words = $sphinx->BuildExcerpts ($height_title,'main', $keyword, $options );  
					//$contents = $sphinx->BuildExcerpts ($height_content,'main', $keyword, $options );  
					
					$list[$key]['name'] = $words[0];
					//$list[$key]['contenthtml'] = $contents[0];
				
				}
				*/
				
			}else{
				$idarr = $relationArr;
				$newsidarr = $relationNewsArr;
				
			
			}

			$ids = implode(',',$idarr);
			$list = $Product->query("SELECT inputtime,title,url FROM `v9_product`  WHERE `v9_product`.title!='' AND  `v9_product`.id IN ($ids) AND id !=$id");


			$newsids = implode(',',$newsidarr);
			$likenewslist = $Product->query("SELECT inputtime,title,url FROM `v9_news`  WHERE `v9_news`.title!='' AND  `v9_news`.id IN ($newsids)");

			//精华推荐
			$goodArr = $Product->query("SELECT `v9_product`.*,v9_position_data.* FROM `v9_product` 
left join `v9_position_data` on  `v9_product`.id=`v9_position_data`.id  WHERE  `v9_product`.title!='' AND v9_product.catid IN ($arrchildid )  AND v9_product.id !=$id AND  v9_position_data.posid IN (1,2,3,4,5,6,7,8,9,10)  order by `v9_product`.id desc limit 0,10");

			//热文排行
			$rankArr = $Product->query("SELECT `v9_product`.* FROM `v9_product` WHERE  `v9_product`.title!='' AND  catid IN ($arrchildid )   ORDER BY `v9_product`.id DESC LIMIT 6 , 10");

			//图片列表
			$imgArr = $Product->query("SELECT `v9_product`.* FROM `v9_product` WHERE  `v9_product`.title!='' AND catid IN ($arrchildid ) AND thumb!=''   ORDER BY `v9_product`.id DESC LIMIT 0 , 4");

			//热门产品
			$hotArr = $Product->query("SELECT `v9_product`.*,v9_product.thumb as newsthumb,v9_position_data.* FROM `v9_product` 
left join `v9_position_data` on  `v9_product`.id=`v9_position_data`.id  WHERE  `v9_product`.title!='' AND  v9_product.thumb!='' AND v9_position_data.posid in (1,2,3,4,5,6,7,8,9)   order by `v9_product`.id desc limit 0,10");


			//热门新闻
			$hotProduct = array_slice($likenewslist,0,10);


			$this->assign('goodArr',$goodArr);// 精华推荐
			$this->assign('rankArr',$rankArr);// 热文排行
			$this->assign('imgArr',$imgArr);// 图片列表
			$this->assign('hotArr',$hotArr);// 热门新闻
			$this->assign('hotProduct',$hotProduct);//热门新闻
			
			$this->assign('catid',$catid);
			$this->assign('keywordList',$keywordList);// 关键词
			$newsArr[0]['content'] = $this->_tagLink($newsArr[0]['content'],$keywordList);
			$this->assign('newsArr',$newsArr[0]);// 赋值数据集

			
			$this->assign('listlike',array_slice($list,0,10));
			$this->assign('list',array_slice($list,10,-1));// 赋值数据集

			$this->assign('likenewslist',array_slice($likenewslist,10,-1));// 相似新闻


			//SEO相关
			if(is_array($seo_Arr)&&count($seo_Arr)){
				$keys = implode(',',array_unique($seo_Arr));
			}else{
				$keys = implode(',',array_unique($keywordArr));
			}
			
			//SEO相关
			$SEO['title'] = $title.'-'.$catname.'-都市家建材网';
			$SEO['keywords'] =  $keys.','.$catname.',都市家建材网,建材网,建材网站';
			$SEO['description'] = strip_tags(str_replace('"',' ',$SeoDescription)).'-都市家建材网,中国最全的建材种类行业门户网站.';
			$this->assign('SEO',$SEO);// SEO相关
			
			//导航
			$NAV_LIST = '<a href="http://www.dushijia.com" title="网站首页" target="_blank">网站首页</a> &gt; 
			<a href="http://product.dushijia.com" title="建材产品" target="_blank">建材产品</a> &gt; 
			<a href="'.$parentUrl.'" title="'.$parentName.'" target="_blank">'.$parentName.'</a> &gt; 
			<a href="'.$caturl.'" title="'.$catname.'" target="_blank">'.$catname.'</a> &gt; '.$title;
			$this->assign('NAV_LIST',$NAV_LIST);


			$this->display(); // 输出模板

		}else{
			header("HTTP/1.0 404 Not Found");
			header('Location: http://www.dushijia.com/error/404.html');
			exit;
		
		}
	
	}


	//改变标签关键字
	private function _tagLink($content,$posttags) {
		
		$match_num_from = 1;
		$match_num_to = 10; 
		//$posttags = get_the_tags();
		
		if ($posttags) {
			 //usort($posttags, "tag_sort");
			 foreach($posttags as $tag) {
				 $link = 'http://www.dushijia.com/tag/show/'.$tag['pinyin'].'_1_1_'.urlencode($tag['name']).'.shtml';
				 $keyword = $tag['name'];
				  
				 //连接代码
				 $cleankeyword = stripslashes($keyword);
				 $url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),'查看所有%s相关的产品')."\"";
				 $url .= ' target="_blank" class="tag_link"';
				 $url .= ">".addcslashes($cleankeyword, '$')."</a>";
				 $limit = rand($match_num_from,$match_num_to);
			
				//不连接的代码
				 $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
				
				//$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
				
				$cleankeyword = preg_quote($cleankeyword,'\'');
					$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
				$content = preg_replace($regEx,$url,$content,$limit);
				$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
			 }
			
		 }
		return $content;
	}
	

}